package cn.edu.ecut.se2024.Servlet;

import java.io.IOException;
import java.util.List;
import cn.edu.ecut.se2024.User.Admin;
import cn.edu.ecut.se2024.Service.adminservice;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;


/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doPost(request, response);}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("uname");
	    String password = request.getParameter("pwd");
		adminservice adminService = new adminservice();
        // 调用 AdminService 类中的方法获取所有管理员信息
        List<Admin> admins = adminService.getAllAdmins();
        // 进行身份验证，这里简单地比较用户名和密码
        int a=0;
        for(int i=0;i<admins.size();i++) {
        	if ("zhangsan".equals(username) && "123456".equals(password)) {
        		// 登录成功，重定向到欢迎页面
        		a=1;
        		response.sendRedirect("/jsp/welcome.jsp");
        	} 
        }
        if(a==0) {
        	// 登录失败，返回登录页面并显示错误消息
            request.setAttribute("errorMessage", "Invalid username or password");
            response.sendRedirect("/jsp/login.jsp");
        }
	}

}